<template>
  <el-tabs tab-position="left"
           type="border-card"
           v-model="activeName"
           style="margin: 20px;
                 height: calc(100% - 42px);"
           class="tabs">
    <el-tab-pane name="first">
      <template #label>
        <div class="icon-text-container">
          <el-icon size="35">
            <UserFilled/>
          </el-icon>
          <span>基本信息</span>
        </div>
      </template>
      <el-form label-width="100px"
               label-position="left"
               style="width: 400px;
                      margin-left: 100px">
        <el-form-item label="用户姓名">
          <el-input v-model="employee.username"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="employee.phone"/>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="employee.gender">
            <el-radio label="男" value="1"/>
            <el-radio label="女" value="2"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号ID">
          <el-input v-model="employee.jobNumber" disabled/>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="employee.idNumber" disabled/>
        </el-form-item>
        <el-form-item label="出生年月">
          <el-date-picker v-model="employee.birthday"
                          type="date"
                          placeholder="选择日期"
                          style="width: 100%;"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="employee.email"/>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="employee.address"/>
        </el-form-item>
        <el-form-item label="员工职位">
          <el-select placeholder="请选择员工职位" v-model="employee.role" disabled>
            <el-option v-for="item in roleArr" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="employee.status">
            <el-radio label="激活" value="1"/>
            <el-radio label="空闲" value="0"/>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入职时间">
          <el-input v-model="employee.createTime" disabled/>
        </el-form-item>
        <el-button type="primary"
                   @click="save"
                   style="width: 400px;">保存
        </el-button>
      </el-form>

    </el-tab-pane>
    <el-tab-pane name="second">
      <template #label>
        <div class="icon-text-container">
          <el-icon size="35">
            <PictureFilled/>
          </el-icon>
          <span>我的头像</span>
        </div>
      </template>
      <el-row :gutter="30">
        <el-col :span="14">
          <el-form style="width: 300px;margin-left: 100px">
            <el-form-item>
              <el-upload
                  v-model:file-list="fileList"
                  v-model:action="actionUrl"
                  name="file"
                  :limit="1"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-dialog v-model="dialogVisible" style="width: 800px; padding: 30px;">
              <img style="width: 740px"
                  :src="dialogImageUrl"
                  :alt="dialogImageUrl"/>
            </el-dialog>
            <el-button type="primary"
                       @click="saveAvatar"
                       style="width: 150px;">保存
            </el-button>
          </el-form>
        </el-col>

        <el-col :span="10">
          <div class="demo-fit">
            <div class="block">
              <span class="title">用户头像</span>
              <el-avatar shape="square" :size="100"
                         :src="BASE_URL + employee.avatar"/>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-tab-pane>
    <el-tab-pane name="third">
      <template #label>
        <div class="icon-text-container">
          <el-icon size="35">
            <Tools/>
          </el-icon>
          <span>密码管理</span>
        </div>
      </template>
      <el-form label-width="100px"
               label-position="left"
               style="width: 400px;
                      margin-left: 100px">
        <el-form-item label="旧密码">
          <el-input type="password" v-model="from.oldPassword"/>
        </el-form-item>
        <el-form-item label="新的密码">
          <el-input type="password" v-model="from.newPassword"/>
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input type="password" v-model="from.confirmPassword"/>
        </el-form-item>
        <el-button type="primary"
                   @click="savePassword"
                   style="width: 400px;">保存
        </el-button>

      </el-form>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import store from "@/store";
import router from "@/router";

const activeName = ref('first');

const id = new URLSearchParams(window.location.search).get('id');

const roleArr = ref([]);
onMounted(() => {
  loadDictOptions(roleArr, 'role');
});

const employee = ref({})
const findAll = (id) => {
  console.log(id)
  axios.get(BASE_URL + '/v1/employee/select?id=' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          employee.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  findAll(id);
})
const save = () => {
  if (employee.value.username === '' || !employee.value.username) {
    errorInfo('请输入员工姓名');
    return;
  }
  if (employee.value.phone === '' || !employee.value.phone) {
    errorInfo('请输入员工手机号');
    return;
  }
  if (employee.value.phone.length !== 11) {
    errorInfo('请输入正确的11位手机号');
    return;
  }
  let data = qs.stringify(employee.value)
  ElMessageBox.confirm('确认保存吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.post(BASE_URL + '/v1/employee/save', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('保存成功!');
            findAll(id)
            activeName.value = 'first';
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    Info('已取消保存');
    findAll(id)
  });

};

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
}
/**图片上传相关代码结束**/
const saveAvatar = () => {
  if (fileList.value.length === 0) {
    errorInfo('请选择图片');
    return;
  }
  let data = qs.stringify({
    id: id,
    avatar: fileList.value[0].response.data
  })
  ElMessageBox.confirm('确认保存吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.post(BASE_URL + '/v1/employee/save', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('保存成功!');
            store.dispatch('updateAvatar', fileList.value[0].response.data);
            fileList.value = [];
            findAll(id)
            activeName.value = 'second';
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消保存');
  });
}

const from = ref({
  id: id,
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const savePassword = (id) => {
  if (!from.value.oldPassword) {
    errorInfo('请输入旧密码');
    return;
  }
  if (!from.value.newPassword) {
    errorInfo('请输入新密码');
    return;
  }
  if (!from.value.confirmPassword) {
    errorInfo('请输入确认密码');
    return;
  }

  let data = qs.stringify(from.value);

  ElMessageBox.confirm('确认保存吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.put(BASE_URL + '/v1/employee/savePassword', data)
        .then(response => {
          if (response.data.code === 2000) {
            // 弹出提示用户需要重新登录的对话框
            ElMessageBox.alert('您的密码已成功更新，请重新登录以继续使用系统。', '提示', {
              customClass: 'custom-message-box',
              confirmButtonText: '确定',
              type: 'success',
              draggable: true,
              callback: () => {
                // 用户点击确定后执行跳转到登录页
                router.push('/login');
              }
            });
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    Info('已取消保存');
  });
};
</script>

<style scoped></style>
<style>
.tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.icon-text-container {
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中（如果需要） */
  text-align: center; /* 确保文本也居中 */
}

.icon-text-container span {
  display: block;
  margin-top: 8px; /* 调整图标与文本之间的间距 */
}

.el-tabs--left.el-tabs--border-card .el-tabs__item.is-left {
  width: 100px;
  height: 100px;
  text-align: center;
}

.el-tabs__item is-left is-active {
  padding: 0;
}

.el-form-item--label-left .el-form-item__label {
  text-align: justify;
}

.demo-fit {
  display: flex;
  text-align: center;
  justify-content: space-between;
}

.demo-fit .block {
  flex: 1;
  display: flex;
  flex-direction: column;
  flex-grow: 0;
}

.demo-fit .title {
  margin-bottom: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}
</style>